﻿using System;
using System.Linq;
using Shell.PocoDot;

namespace Shell.DomainDot
{
    public class WithMany<TPocoDot> : IDisposable
        where TPocoDot : PocoDotBase
    {
        private bool disposed;

        public WithMany(Guid mainKey, IDataContext<TPocoDot> repository, IRepository relationship)
        {
            this.MainKey = mainKey;
            this.Repository = repository;
            this.RelationRepository = relationship;
        }

        protected Guid MainKey { get; private set; }

        protected IDataContext<TPocoDot> Repository { get; private set; }

        protected IRepository RelationRepository { get; private set; }

        public IQueryable<TPocoDot> Instances
        {
            get
            {
                var keys = this.RelationRepository.ReadAll(this.MainKey);
                return this.Repository.Read(keys);
            }
        }

        public void Bind(Guid key)
        {
            this.RelationRepository.Bind(this.MainKey, key);
        }

        public void Release(Guid key)
        {
            this.RelationRepository.Release(this.MainKey, key);
        }

        public TPocoDot Create()
        {
            try
            {
                var dot = this.Repository.Create();
                this.Bind(dot.Id);
                return dot;
            }
            catch (Exception) //TODO
            {
                throw;
            }
        }

        public void Delete(Guid key)
        {
            try
            {
                this.Release(key);
                this.Repository.Delete(key);
            }
            catch (Exception) //TODO
            {
                throw;
            }
        }

        public int Submit()
        {
            try
            {
                int count1 = this.Repository.Submit();
                int count2 = this.RelationRepository.Submit();
                return count1 + count2;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (!this.disposed)
                {
                    this.Repository = null;
                    this.RelationRepository = null;
                }
                this.disposed = true;
            }
        }
    }
}
